package com.kyang.musiconline.dao;

import cn.hutool.core.util.IdUtil;
import com.kyang.musiconline.model.Vinyl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * @author kyang
 */
@Repository
public class VinylDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public boolean insert(Vinyl vinyl) {
        String id = IdUtil.getSnowflake(1L, 1L).nextIdStr();
        Date now = new Date();
        vinyl.setCreateDate(now);
        vinyl.setUpdateDate(now);
        vinyl.setId(id);
        vinyl.setMusicCover("./static/img/ad-trance.jpg");
        String sql = "insert into music values (?,?,?,?,?,?,?,?,?,?,?)";
        int count = jdbcTemplate.update(sql, vinyl.convertObjects());
        return count == 1;
    }

    public boolean update(Vinyl vinyl) {
        String sql = "update music set music_name=?,music_author=?,music_name=?,music_intro=?,issuing_date=?,music_price=?,music_cover=?,update_date=? where id=? and is_delete=0";
        Object[] objects = new Object[9];
        objects[0] = vinyl.getMusicName();
        objects[1] = vinyl.getMusicAuthor();
        objects[3] = vinyl.getMusicIntro();
        objects[4] = vinyl.getIssuingDate();
        objects[5] = vinyl.getMusicPrice();
        objects[6] = vinyl.getMusicCover();
        objects[7] = new Date();
        objects[8] = vinyl.getId();
        int count = jdbcTemplate.update(sql, objects);
        return count == 1;
    }

    public boolean deleteById(String vinylId) {
        String sql = "update music set is_delete = 1, update_date = '" + new Date() + "'where id = '" + vinylId + "'";
        int count = jdbcTemplate.update(sql);
        return count == 1;
    }

    public Vinyl getVinylById(String vinylId) {
        String sql = "select * from music where id = ? and is_delete=0";
        Object[] objects = new Object[1];
        objects[0] = vinylId;
        return jdbcTemplate.queryForObject(sql, new Vinyl(), objects);
    }

    public List<Vinyl> getTwelveVinyls() {
        String sql = "select * from music where is_delete=0 order by id desc limit 12";
        return jdbcTemplate.query(sql, new Vinyl());
    }

    public List<Vinyl> getAllVinylByUser(String userId) {
        String sql = "select * from music where music_user = ? and is_delete=0";
        Object[] objects = new Object[1];
        objects[0] = userId;
        return jdbcTemplate.query(sql, new Vinyl(), objects);
    }

    public List<Vinyl> getVinylByKeyWords(String keywords) {
        String sql = "select * from music where (music_name like '%" + keywords + "%' or music_author like '%" + keywords + "%') and is_delete=0";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Vinyl.class));
    }
}
